<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>ajax</title>
	<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>
<body>
	<form action="" id="form_login">
		用户名<input type="text" name="username">
		密码<input type="password" name="password">
		<input type="submit" value="登录">
	</form>
	<!-- 加载 -->
		<button id="btn_load">加载用户信息</button>
	<div id="msg">
		
	</div>

	<script type="text/javascript">
		var token;	//token全局
		var form_login = document.querySelector("#form_login");
		var msg = document.querySelector("#msg");
		var btn_load = document.querySelector("#btn_load")
		btn_load.onclick = function(){
			//准备参数
			var param = {
				page:1,
				pageSize:10
			}
			var xhr = new XMLHttpRequest();	
			//将一个对象序列化（转换成qs)
			var url = "http://localhost:7788/baseUser/pageQuery?"+$.param(param)
			xhr.open("GET",url)
			xhr.setRequestHeader("Authorization",token)
			xhr.send();
			xhr.onreadystatechange = function(){
				if (xhr.readyState === 4) {
					if (xhr.status ===200) {
						let resp = JSON.parse(xhr.response)
						if (resp.status === 200) {
							msg.innerText = JSON.stringify(resp.data)
						}else{
							msg.innerText = resp.message;
						}
					}
				}
			}
		}
		//提交登录
		form_login.onsubmit = function(event){
			// alert(1);
			//获取表单数据
			var username = document.querySelector("#form_login > input[name=username]").value;
			var password = document.querySelector("#form_login > input[name=password]").value;
			// alert(username+":"+password)
			
			//交互
			//初始化
			var xhr = new XMLHttpRequest();
			//设置请求行
			let url = "http://localhost:7788/user/login"
			xhr.open("POST",url);
			//设置请求头
			xhr.setRequestHeader("Content-Type","application/json")

			//设置请求头
			var data = {username,password};
			xhr.send(JSON.stringify(data));
			//监听
			xhr.onreadystatechange = function(){
				//判断代理状态
				if(xhr.readyState === 4){
					// 判断网络响应状态
					if (xhr.status === 200) {
						let resp = JSON.parse(xhr.response)
						// 判断业务状态
						if(resp.status === 200){
							msg.innerText = "登录成功，token为："+resp.data.token;
							token = resp.data.token;

						}else{
							msg.innerText = resp.massage;
						}
					}
				}
			}
			event.preventDefault();
			
		}
	</script>
</body>
</html>